function [ pdffiles ] = Fig2Pdf( figfiles, portraitTf )
%FIG2PDF Converts saved figures to pdf
%   files: list of files to convert, leave [] to do all files in current
%           folder

if ~exist('portraitTf', 'var') || ~islogical(portraitTf)
    portraitTf = true;
end

if ~exist('figfiles', 'var') || isempty(figfiles)
    d = dir('*.fig');
    figfiles = {d.name}';
    cdir = cd;
    for f = 1:length(figfiles)
        figfiles{f} = [cdir '\' figfiles{f}];
    end
end

pdffiles = cell(size(figfiles));
totalTimeElapsed = 0;
for f = 1:length(figfiles)
    [pdffiles{f} elapsedTime] = saveFigureAsPdf(figfiles{f}, portraitTf);
    totalTimeElapsed = totalTimeElapsed + elapsedTime;
    disp([num2str(f) '/' num2str(length(figfiles)) ': ' figfiles{f} ' --> ' pdffiles{f}]);
    timeRemaining = ((totalTimeElapsed / f) * length(figfiles)) - totalTimeElapsed; % in seconds
    disp(['Estimated time remaining: ' num2str(timeRemaining/60) ' minute(s)']);     
end

end

function [ pdfFilename elapsedTime ] = saveFigureAsPdf( filename, portraitTf )

tStart = tic;

pdfFilename = [filename(1:end-3) 'pdf'];

fig = openfig(filename, 'new', 'invisible');
set(fig, 'PaperUnits', 'centimeters');
set(fig, 'PaperType', 'A4');
if portraitTf
    set(fig, 'PaperOrientation', 'portrait');
    set(fig, 'PaperPositionMode', 'manual');
    set(fig, 'PaperPosition', [0.6 0.6 19.7 28.4]);
else
    set(fig, 'PaperOrientation', 'landscape');
    set(fig, 'PaperPositionMode', 'manual');
    set(fig, 'PaperPosition', [0.6 0.6 28.4 19.7]);
end

print(['-f' num2str(fig)], pdfFilename, '-dpdf', '-r600');
delete(fig);

elapsedTime = toc(tStart);

end